/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if (list1 == NULL)
        return list2;
    if (list2 == NULL)
        return list1;
    struct ListNode* tail1 = list1;
    struct ListNode* tail2 = list2;
    struct ListNode* head = NULL;
    struct ListNode* tail = NULL;
    while (tail1 && tail2)
    {
        if (head == NULL)
        {
            if (tail1->val <= tail2->val)
            {
                head = tail = tail1;
                tail1 = tail1->next;
            }
            else
            {
                head = tail = tail2;
                tail2 = tail2->next;
            }
        }
        else
        {
            if (tail1->val <= tail2->val)
            {
                tail->next = tail1;
                tail1 = tail1->next;
                tail = tail->next;
            }
            else
            {
                tail->next = tail2;
                tail2 = tail2->next;
                tail = tail->next;
            }
        }
    }
    if (tail1)
        tail->next = tail1;
    if (tail2)
        tail->next = tail2;
    return head;
}